// Problem 170: Find the largest 0 to 9 pandigital that can be formed by concatenating products
// Take the number 6 and multiply it by each of 1273 and 9854:
// 6 × 1273 = 7638
// 6 × 9854 = 59124
// By concatenating these products we get the 1 to 9 pandigital 763859124. We will call 763859124 the "concatenated product of 6 and (1273,9854)". Notice too, that the concatenation of the input numbers, 612739854, is also 1 to 9 pandigital.
// The same can be done for 0 to 9 pandigital numbers.
// What is the largest 0 to 9 pandigital 10-digit concatenated product of an integer with two or more other integers, such that the concatenation of the input numbers is also a 0 to 9 pandigital 10-digit number?

package main

import (
	"fmt"
	"projecteuler/euler"
	"sort"
	"strconv"
	"strings"
)

func p170() {

	allStr := euler.Permutations(10, "1234567890")
	var num []int
	max := 0
	for digit := 98; digit > 12; digit-- {
		num = num[0:0]
		for _, v := range allStr {
			if strings.HasPrefix(v, "9") {
				x, _ := strconv.Atoi(v)
				if x%digit == 0 {
					num = append(num, x)
				}
			} else {
				continue
			}
		}
		sort.Ints(num)
		for i := len(num) - 1; i > 0; i-- {
			if check170(num[i], digit) {
				if num[i] > max {
					max = num[i]
				}
				break
			}
		}
	}
	fmt.Println("Problem 170:", max)
}

func check170(n, digit int) bool {
	low := n % 10000
	if low < 1000 {
		return false
	}
	high := n / 10000
	if low%digit == 0 && high%digit == 0 {
		str := fmt.Sprintf("%d%d%d", digit, low/digit, high/digit)
		if len(str) != 10 {
			return false
		}
		if euler.IsUniqueDigits(str) {
			// fmt.Printf("%d*%d=%d\n", digit, high/digit, high)
			// fmt.Printf("%d*%d=%d\n", digit, low/digit, low)
			return true
		}
	}
	return false
}
